package cmd

import (
	"gitee.com/feimos/dm/core"
	"gitee.com/feimos/dm/utils"
	"github.com/urfave/cli/v2"
	"log"
	"os"
	"path/filepath"
	"strings"
)

// RemoveCommand 处理 remove subcommand
func RemoveCommand(c *cli.Context) error {

	name := core.UnifyPath(c.Args().First())
	root, err := filepath.Abs(filepath.Dir(os.Args[0]))

	if err != nil {
		return err
	}

	yamlContent, err := core.LoadYaml(root)

	if err != nil {
		log.Println(err)
		log.Fatalln("try to use \"dm init\" to generate config file")
	}

	if !strings.Contains(name, "*") {
		err = core.RemoveOneDocument(yamlContent, name, true)

		if err != nil {
			return err
		}
	} else {

		err = core.RemoveGlob(yamlContent, name)

		if err != nil {
			return err
		}
	}

	ignoreList := core.LoadIgnoreFile(root, false)
	err = utils.RemoveAllEmptyDir(root, ignoreList, true)

	if err != nil {
		return err
	}

	return nil
}
